import { Injectable, NotFoundException, BadRequestException } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { Payment } from './payment.entity';
import { CreatePaymentDto } from './dto/create-payment.dto';
import { User } from '../user/user.entity';
import { Order } from '../order/order.entity';

@Injectable()
export class PaymentService {
  constructor(
    @InjectRepository(Payment)
    private readonly paymentRepository: Repository<Payment>,
    @InjectRepository(Order)
    private readonly orderRepository: Repository<Order>,
  ) {}

  async create(user: User, dto: CreatePaymentDto): Promise<Payment> {
    const order = await this.orderRepository.findOne({ where: { id: dto.orderId }, relations: ['user'] });
    if (!order) throw new NotFoundException('订单不存在');
    if (order.user.id !== user.id) throw new BadRequestException('无权支付该订单');
    // 这里只做模拟，实际应对接第三方支付
    const payment = this.paymentRepository.create({
      user,
      order,
      amount: order.totalPrice,
      method: dto.method || 'alipay',
      status: 'paid', // 模拟直接支付成功
      transactionId: 'MOCK_' + Date.now(),
    });
    return this.paymentRepository.save(payment);
  }

  async findByOrder(user: User, orderId: number): Promise<Payment> {
    const payment = await this.paymentRepository.findOne({ where: { order: { id: orderId }, user: { id: user.id } }, relations: ['order'] });
    if (!payment) throw new NotFoundException('支付记录不存在');
    return payment;
  }
}
